import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { message } from 'antd';
import { DATA_ENTRY, AdvancedSearch, NoQueryC, QuickQueryC, TableC, ModalC, PrimaryC, IconC, PrimaryGhostC } from '../../../comps';
import moment from 'moment';
import UnusualInfoC from './unusualInfoC';
import uuid from 'es6-uuid';
import Mystyle from './index.less';
import colors from '../../../css/colors';
import ContentPackage from '@/src/comps/other/contentPackage';
import { exportFile } from 'table-xlsx';
import { cloneDeep } from 'lodash';

class OperationOverallP extends PureComponent {
  constructor() {
    super();
    this.state = {
      queryStartDate: undefined, //查询开始间
      queryEndDate: undefined, //查询结束时间
      compareStartDate: undefined, //比对开始时间
      compareEndDate: undefined, //比对结束时间
      firstQueryFlag: false, //是否第一次点击查询按钮
      isReset: false, //是否重置
      columns: undefined, //表头
      dataSource: undefined, //表格数组
      unusualInfo: {}, //异常信息
      visible: false, //展示异常信息
      fixed: true, //是否冻结
      queryType: 'month', //默认日期组件展示的是年月
      showYear: false, //点击查询按钮确定展示按年份还是按月份展示表头
    };
  }
  componentDidMount() {}
  //取年的时间区间
  formatDate = (year) => {
    if (!year) return {};
    let obj = {};
    if (moment().format('YYYY') == year.format('YYYY')) {
      obj.endDate = moment().format('YYYY-MM-DD');
    } else {
      obj.endDate = year.format('YYYY-12-31');
    }
    obj.startDate = year.format('YYYY-01-01');
    return obj;
  };

  // 查询数据
  searchData = (e) => {
    if (!this.state.firstQueryFlag) {
      this.setState({
        firstQueryFlag: true,
      });
    }
    if (e) {
      if (e.compareDate) {
        if (!e.queryDate && e.compareDate) {
          message.warning('对比日期存在时，查询日期必填！');
          return;
        }
        if (moment(e.compareDate).format('YYYYMM') == moment(e.queryDate).format('YYYYMM')) {
          message.warning('查询日期和对比日期不可以相同！');
          return;
        }
      }

      this.setState(
        {
          isReset: false,
          searchData: {
            queryStartDate: e.queryType == 'month' ? this.state.queryStartDate : this.formatDate(e.queryDate).startDate,
            queryEndDate: e.queryType == 'month' ? this.state.queryEndDate : this.formatDate(e.queryDate).endDate,
            compareStartDate: e.queryType == 'month' ? this.state.compareStartDate : this.formatDate(e.compareDate).startDate,
            compareEndDate: e.queryType == 'month' ? this.state.compareEndDate : this.formatDate(e.compareDate).endDate,
            tenantIdList: e.tenantIdList,
          },
        },
        () => {
          //点击查询的时候 赋值表头的日期
          this.setState({
            query: e.queryDate,
            compare: e.compareDate,
            showYear: e.queryType == 'year',
          });
          console.log(this.state.searchData);
          this.queryTableList();
        },
      );
    }
  };
  //获取时间区间
  dateOnchange = (e, type) => {
    let startDate = type + 'StartDate';
    let endDate = type + 'EndDate';
    //不满一月，最后一天是当天
    if (e && moment(e.endDate).format('YYYYMMDD') > moment().format('YYYYMMDD')) e.endDate = moment().format('YYYY-MM-DD');
    this.setState({
      [startDate]: e?.startDate,
      [endDate]: e?.endDate,
    });
    //默认取前一月
    if (e?.startDate && type == 'query') this.compareDateRef?.setDate(moment(e.startDate, 'YYYY-MM').subtract('1', 'month'));
  };
  //查询结果列表
  queryTableList = () => {
    const { searchData } = this.state;
    this.setState({
      queryLoading: true, //loading
    });
    this.props.dispatch({
      type: 'operationOverallM/getResultList',
      payload: {
        ...this.state.searchData,
        queryStartDate: searchData.queryStartDate || moment().format('YYYY-MM-01'), //当无查询时间，则默认当天
        queryEndDate: searchData.queryEndDate || moment().format('YYYY-MM-DD'),
      },
      callback: (data) => {
        if (data) {
          //成功
          if (data?.unusualList) {
            let obj = data.unusualList;
            //有异常信息 则赋值并展示弹窗，否则不处理
            if (obj.productNumList?.length || obj.productScaleist?.length || obj.tradeList?.length) {
              this.setState({
                unusualInfo: obj,
                visible: true,
              });
            } else {
              //如果没有 则置空
              this.setState({
                unusualInfo: {},
                visible: false,
              });
            }
          }
          data?.resultList?.map((item) => {
            item.key = uuid(16);
          });
          //拿到合计行
          this.setState({
            totalObj: data?.resultList[data?.resultList.length - 1],
          });
          this.setState(
            {
              columns: data?.columns || [],
              dataSource: data?.resultList || [],
              queryLoading: false,
            },
            () => {
              //重新查询都以产品规模为排序数据
              this.QuickQuery.setSelect('queryProductScale');
            },
          );
        } else {
          //查询失败
          this.setState({
            columns: [],
            dataSource: [],
            queryLoading: false,
          });
        }
      },
    });
  };

  //根据对应属性排序
  compareFn = (property) => {
    return function (a, b) {
      var value1 = a[property] || 0;
      var value2 = b[property] || 0;
      return value2 - value1;
    };
  };
  //设置差额前5 前10
  settingTopBottom = (type) => {
    const { dataSource } = this.state;
    let tempArr = JSON.parse(JSON.stringify(dataSource));
    //进入之后 删除上一次得前后几名
    tempArr.map((item) => {
      if (item.rank) delete item.rank;
    });
    //按照属性排序 排序之后 取大于0得数组找出前5。小于0得数组找出倒数5，
    tempArr.sort(this.compareFn(type));
    let topArr = tempArr.filter((item) => item[type] > 0);
    let bottomArr = tempArr.filter((item) => item[type] < 0);
    //给每个元素设置rank 排序编号 1，2，3，4，5；-1，-2，-3，-4，-5
    topArr.map((item, index) => {
      if (index < 5) {
        //正增长前5的
        item.rank = index + 1;
      }
    });
    bottomArr.map((item, index, temp) => {
      if (temp.length - 6 > 0) {
        if (index > temp.length - 6) {
          //负增长倒数5位
          item.rank = index - temp.length;
        }
      } else {
        //负增长低于5个得
        item.rank = index - temp.length;
      }
    });

    //表格元素加上排序值
    dataSource.map((item) => {
      tempArr.map((x) => {
        if (item.key == x.key) {
          item.rank = x.rank;
        }
      });
    });

    this.setState(
      {
        dataSource: [...dataSource],
      },
      () => {
        //排序处理之后 加上总计行
        dataSource.push(this.state.totalObj);
        this.setState({
          dataSource,
        });
      },
    );
  };

  //表格
  showTable = () => {
    const { dataSource, currentRank, query, compare, fixed, showYear, queryLoading } = this.state;
    this.columns = [
      {
        key: 'tenantName',
        title: '租户名称',
        fixed: !compare ? undefined : fixed ? 'left' : undefined,
        width: 250,
        type: 'maxContent',
      },
      {
        key: 'productScale',
        title: `产品规模${!compare ? '(亿)' : ''}`,
        type: 'money',
        children: [
          {
            key: 'queryProductScale',
            title: query ? (showYear ? `${query.format('YYYY')}年底(亿)` : `${query.format('YYYY.MM')}月底(亿)`) : '',
            type: 'money',
          },
          {
            key: 'compareProductScale',
            title: compare ? (showYear ? `${compare.format('YYYY')}年底(亿)` : `${compare.format('YYYY.MM')}月底(亿)`) : '',
            type: 'money',
          },
          {
            key: 'differenceScale',
            title: '规模对比(亿)',
            type: 'money',
            onCell: (record, rowIndex) => {
              let cellProps = {};
              if (currentRank == 'differenceScale') {
                if (record.rank > 0) {
                  cellProps.style = {
                    background: colors.top5Colors[record.rank - 1],
                  };
                } else if (record.rank < 0) {
                  cellProps.style = {
                    background: colors.bottom5Colors[5 - Math.abs(record.rank)],
                  };
                }
              }
              return cellProps;
            },
          },
        ],
      },
      {
        key: 'productNum',
        title: `产品数量`,
        type: 'number',
        children: [
          {
            key: 'queryProductNum',
            title: query ? (showYear ? `${query.format('YYYY')}年底` : `${query.format('YYYY.MM')}月底`) : '',
            type: 'number',
          },
          {
            key: 'compareProductNum',
            title: compare ? (showYear ? `${compare.format('YYYY')}年底` : `${compare.format('YYYY.MM')}月底`) : '',
            type: 'number',
          },
          {
            key: 'differenceNum',
            title: '数量对比',
            type: 'number',
            onCell: (record, rowIndex) => {
              let cellProps = {};
              if (currentRank == 'differenceNum') {
                if (record.rank > 0) {
                  cellProps.style = {
                    background: colors.top5Colors[record.rank - 1],
                  };
                } else if (record.rank < 0) {
                  cellProps.style = {
                    background: colors.bottom5Colors[5 - Math.abs(record.rank)],
                  };
                }
              }
              return cellProps;
            },
          },
        ],
      },
      {
        key: 'tradeNum',
        title: '交易数量',
        type: 'number',
        children: [
          {
            key: 'queryTradeNum',
            title: query ? (showYear ? `${query.format('YYYY')}` : `${query.format('YYYY.MM')}`) : '',
            type: 'number',
          },
          {
            key: 'compareTradeNum',
            title: compare ? (showYear ? `${compare.format('YYYY')}` : `${compare.format('YYYY.MM')}`) : '',
            type: 'number',
          },
          {
            key: 'differenceTradeNum',
            title: '交易数对比',
            type: 'number',
          },
        ],
      },
      {
        key: 'menuVisits',
        title: '菜单点击数',
        type: 'number',
        children: [
          {
            key: 'queryMenuVisits',
            title: query ? (showYear ? `${query.format('YYYY')}` : `${query.format('YYYY.MM')}`) : '',
            type: 'number',
          },
          {
            key: 'compareMenuVisits',
            title: compare ? (showYear ? `${compare.format('YYYY')}` : `${compare.format('YYYY.MM')}`) : '',
            type: 'number',
          },
          {
            key: 'differenceVisits',
            title: '点击数对比',
            type: 'number',
            onCell: (record, rowIndex) => {
              let cellProps = {};
              if (currentRank == 'differenceVisits') {
                if (record.rank > 0) {
                  cellProps.style = {
                    background: colors.top5Colors[record.rank - 1],
                  };
                } else if (record.rank < 0) {
                  cellProps.style = {
                    background: colors.bottom5Colors[5 - Math.abs(record.rank)],
                  };
                }
              }

              return cellProps;
            },
          },
        ],
      },
      {
        key: 'activeMenus',
        title: '活跃菜单(前5)',
        width: 250,
        render: (text) => {
          if ((text ?? '--') == '--') {
            return '--';
          } else {
            let list = text.split(',');
            return (
              <div>
                {list.map((item, index, array) => {
                  return (
                    <span key={index} className={Mystyle.label}>
                      {item}
                      {index != array.length - 1 ? <b style={{ visibility: 'hidden' }}>,</b> : null}
                    </span>
                  );
                })}
              </div>
            );
          }
        },
        children: [
          {
            key: 'queryTopMenus',
            title: query ? (showYear ? `${query.format('YYYY')}` : `${query.format('YYYY.MM')}`) : '',
            width: 250,
            render: (text) => {
              if ((text ?? '--') == '--') {
                return '--';
              } else {
                let list = text.split(',');
                return (
                  <div>
                    {list.map((item, index, array) => {
                      return (
                        <span key={index} className={Mystyle.label}>
                          {item}
                          {index != array.length - 1 ? <b style={{ visibility: 'hidden' }}>,</b> : null}
                        </span>
                      );
                    })}
                  </div>
                );
              }
            },
          },
          {
            key: 'compareTopMenus',
            title: compare ? (showYear ? `${compare.format('YYYY')}` : `${compare.format('YYYY.MM')}`) : '',
            width: 250,
            render: (text) => {
              if ((text ?? '--') == '--') {
                return '--';
              } else {
                let list = text.split(',');
                return (
                  <div>
                    {list.map((item, index, array) => {
                      return (
                        <span key={index} className={Mystyle.label}>
                          {item}
                          {index != array.length - 1 ? <b style={{ visibility: 'hidden' }}>,</b> : null}
                        </span>
                      );
                    })}
                  </div>
                );
              }
            },
          },
        ],
      },
    ];
    let columns = this.columns;
    //如果对比日期没有，则不展示对比列,没有合并表头
    if (!compare)
      columns.map((item) => {
        if (item.children) {
          let children = item.children?.filter((child, index) => index < 1);
          let obj = children[0];
          item.key = obj.key;
          item.width = 150;
          item.type = item.type;
          delete item.children;
        }
      });
    //这里处理有对比日期的列宽
    columns.map((item, key) => {
      if (item.children) {
        item.children.map((child, index) => {
          //调整列宽
          if (child.key == 'queryProductScale' || child.key == 'compareProductScale') {
            child.width = !compare ? child.width || 150 : 130;
          } else {
            child.width = !compare ? child.width || 150 : child.width || 100;
          }
        });
      }
    });
    return (
      <div id={'overallId'}>
        <TableC
          columns={columns || []}
          dataSource={dataSource}
          rowKey='key'
          loading={queryLoading}
          hidePage={true}
          scroll={{ x: 'max-content' }}
          selfScrollY={true}
          rowClassName={(record, index) => {
            //设置最后一列样式
            if (dataSource?.length - 1 == index) {
              return !compare ? Mystyle.fixedtr1 : Mystyle.fixedtr;
            }
          }}
        />
      </div>
    );
  };
  //异常信息
  showModal = () => {
    const { visible, unusualInfo } = this.state;
    const props = {
      visible: visible,
      onOk: () => {
        this.setState({ visible: false });
      },
      onCancel: () => {
        this.setState({ visible: false });
      },
      title: '异常信息',
      footer: (
        <PrimaryC
          title={'确定'}
          onClick={() => {
            this.setState({ visible: false });
          }}
        />
      ),
      // height: 745,
      maskClosable: false,
    };
    return (
      <div>
        <ModalC {...props}>
          <UnusualInfoC unusualInfo={unusualInfo || {}} />
        </ModalC>
      </div>
    );
  };
  //按照什么类型排序，切换他们的类型，并进行前端排序
  sortedTypeChange = (e) => {
    console.log('排序类型：', e);
    if (this.state.isReset) {
      message.warning('您已重置查询字段，请设置条件后执行查询');
    }
    if (!this.state.dataSource?.length) return;
    let obj = { queryProductScale: 'differenceScale', queryProductNum: 'differenceNum', queryMenuVisits: 'differenceVisits' };
    if (this.state.dataSource) {
      this.state.dataSource?.pop();
      this.setState(
        {
          dataSource: this.state.dataSource.sort(this.compareFn(e)), //去掉最后一行排序
        },
        () => {
          this.setState(
            {
              currentRank: obj[e],
            },
            () => {
              this.settingTopBottom(obj[e]);
            },
          );
        },
      );
    }
  };
  //查询范围并更 年月切换
  changeType = (e) => {
    let query = this.state.queryStartDate;
    this.setState(
      {
        queryType: e,
        queryStartDate: undefined,
        queryEndDate: undefined,
        compareStartDate: undefined,
        compareEndDate: undefined,
      },
      () => {
        if (e == 'year' && query) {
          //对比日期倒退一年
          this.compareDateRef.setDate(moment(query).subtract('1', 'year'));
        }
        if (e == 'month') {
          this.compareDateRef.setDate(null);
          this.queryDateRef.setDate(null);
        }
      },
    );
  };
  //年份时间变更
  yearChange = (e, type) => {
    console.log(e);
    //对比日期倒退一年
    if (type == 'query') this.compareDateRef.setDate(moment(e).subtract('1', 'year'));
  };

  render() {
    const { firstQueryFlag, query, compare, totalObj, currentRank, queryType, showYear, visible } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'queryType',
          title: '查询范围',
          type: DATA_ENTRY.SELECT,
          allowClear: false,
          initialValue: 'month',
          dataSource: [
            { value: 'year', title: '按年度' },
            { value: 'month', title: '按月份' },
          ],
          onChange: this.changeType,
        },
        {
          dataIndex: 'queryDate',
          title: '查询日期',
          type: DATA_ENTRY.SINGLEDATE,
          onChange: (e) => this.dateOnchange(e, 'query'),
          // initialValue: moment(new Date(), "YYYY-MM"),
          disableEnd: moment().add('1', 'month'),
          dataType: 'month',
          valueType: 'range',
          allowClear: false,
          onRef: (ref) => (this.queryDateRef = ref),
          hide: queryType == 'year',
        },
        {
          dataIndex: 'compareDate',
          title: '对比日期',
          type: DATA_ENTRY.SINGLEDATE,
          onChange: (e) => this.dateOnchange(e, 'compare'),
          // initialValue: moment(new Date(), "YYYY-MM").subtract('1', "month"),
          disableEnd: moment().add('1', 'month'),
          dataType: 'month',
          valueType: 'range',
          onRef: (ref) => (this.compareDateRef = ref),
          hide: queryType == 'year',
        },
        {
          dataIndex: 'queryDate',
          title: '查询日期',
          type: DATA_ENTRY.SINGLEDATE,
          onChange: (e) => this.yearChange(e, 'query'),
          dataType: 'year',
          allowClear: false,
          hide: queryType == 'month',
          onRef: (ref) => (this.queryDateRef = ref),
        },
        {
          dataIndex: 'compareDate',
          title: '对比日期',
          type: DATA_ENTRY.SINGLEDATE,
          onChange: (e) => this.yearChange(e, 'compare'),
          dataType: 'year',
          hide: queryType == 'month',
          onRef: (ref) => (this.compareDateRef = ref),
        },
        {
          dataIndex: 'tenantIdList',
          title: '租户',
          multiple: true,
          type: DATA_ENTRY.TENANT,
          filterTenants: ['HTSC-TEST', 'HTSC-JXZY'], //过滤掉不需要得租户
        },
      ],
      onQuery: this.searchData,
      onClear: () => {
        this.setState(
          {
            isReset: true,
            searchData: {},
            queryType: 'month',
          },
          () => {
            //重置日期区间变量
            this.queryDateRef?.setDate(null);
            this.compareDateRef?.setDate(null);
          },
        );
      },
    };
    //设置导出表格excel的列宽
    let ColOption = [];
    for (let index = 0; index < 15; index++) {
      ColOption.push({ wpx: index == 14 || index == 13 ? 150 : 100 });
    }
    //总计信息的数据整理
    let infoData = [];
    if (totalObj) {
      let totalInfo = {
        differenceScale: [
          showYear ? `${query?.format('YYYY')}年较${compare?.format('YYYY')}` : `${query?.format('YYYY.MM')}月较${compare?.format('YYYY.MM')}`,
          totalObj['differenceScale'] == undefined || totalObj['differenceScale'] == null ? totalObj['differenceScale'] : totalObj['differenceScale'].toFixed(2),
          `${query ? (showYear ? query?.format('YYYY') : query?.format('YYYY.MM')) : moment().format(showYear ? 'YYYY' : 'YYYY.MM')}共`,
          totalObj['queryProductScale'] == undefined || totalObj['queryProductScale'] == null ? totalObj['queryProductScale'] : totalObj['queryProductScale'].toFixed(2),
          '亿元',
        ],
        differenceNum: [
          showYear ? `${query?.format('YYYY')}年较${compare?.format('YYYY')}` : `${query?.format('YYYY.MM')}月较${compare?.format('YYYY.MM')}`,
          totalObj['differenceNum'],
          `${query ? (showYear ? query?.format('YYYY') : query?.format('YYYY.MM')) : moment().format(showYear ? 'YYYY' : 'YYYY.MM')}共`,
          totalObj['queryProductNum'],
          '只',
        ],
        differenceVisits: [
          showYear ? `${query?.format('YYYY')}年较${compare?.format('YYYY')}` : `${query?.format('YYYY.MM')}月较${compare?.format('YYYY.MM')}`,
          totalObj['differenceVisits'],
          `${query ? (showYear ? query?.format('YYYY') : query?.format('YYYY.MM')) : moment().format(showYear ? 'YYYY' : 'YYYY.MM')}菜单点击次数为`,
          totalObj['queryMenuVisits'],
          '次',
        ],
      };
      infoData = totalInfo[currentRank];
    }
    return (
      <ContentPackage
        title='运营总况'
        contentHtml={
          <div className={Mystyle.overall}>
            <div style={{ marginBottom: '20px' }}>
              <AdvancedSearch {...searchProps} />
            </div>

            {firstQueryFlag ? (
              <>
                <div style={{ marginBottom: '15px' }}>
                  <QuickQueryC
                    dataSource={[
                      { value: 'queryProductScale', title: '产品规模' },
                      { value: 'queryProductNum', title: '产品数量' },
                      { value: 'queryMenuVisits', title: '点击次数' },
                    ]}
                    initialValue='queryProductScale'
                    onChange={this.sortedTypeChange}
                    onRef={(ref) => (this.QuickQuery = ref)}
                  />
                </div>
                <div style={{ display: 'flex', marginBottom: '15px', alignItems: 'center' }}>
                  <div className={Mystyle.wrap} style={{ flex: 1 }}>
                    {this.state.compare && infoData?.length ? (
                      <div>
                        <div>{infoData[0]}</div>
                        <div className={infoData[1] > 0 ? Mystyle.red : (infoData[1] ?? '--') == '--' || infoData[1] == 0 ? '' : Mystyle.green}>
                          {infoData[1] ?? '--'}
                          {infoData[4]}
                          {(infoData[1] ?? '--') == '--' || infoData[1] == 0 ? null : <IconC className={Mystyle.arrow} type={infoData[1] > 0 ? 'upRegulate' : 'downRegulate'} />}
                        </div>
                      </div>
                    ) : null}
                    {infoData?.length ? (
                      <div>
                        <div>{infoData[2]}</div>
                        <div>
                          {infoData[3] ?? '--'}
                          {infoData[4]}
                        </div>
                      </div>
                    ) : null}
                  </div>
                  <div style={{ marginLeft: '19px' }}>
                    <PrimaryGhostC
                      title={'导出'}
                      onClick={() => {
                        const dataCopy = cloneDeep(this.state.dataSource);
                        const lastItem = dataCopy.pop();
                        dataCopy.sort((x, y) => -(x.queryProductNum - y.queryProductNum));
                        dataCopy.push(lastItem);
                        exportFile({
                          fileName: `MAAT ${`${query ? query?.format(showYear ? 'YYYY' : 'YYYY.MM') : moment().format(showYear ? 'YYYY' : 'YYYY.MM')}${
                            showYear ? '年' : ''
                          }底系统运维数据.xlsx`}`, // 文件名
                          columns: this.columns, // 表格columns
                          dataSource: dataCopy, // 表格dataSource queryProductNum
                          raw: true,
                          headerCellStyle: {
                            fillFgColorRgb: 'e8efff', // header行的填充颜色
                          },
                        });
                      }}
                    />
                  </div>
                </div>
                {this.showTable()}
                {visible ? this.showModal() : null}
              </>
            ) : (
              <NoQueryC />
            )}
          </div>
        }
      />
    );
  }
}
export default connect(({ operationOverallM, loading }) => ({
  operationOverallM,
  loading,
}))(OperationOverallP);
